<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { SystemApi } from '#/api/system/system';
import type { UserApi } from '#/api/system/user';

import { computed, nextTick, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { ElMessage } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getSystemList } from '#/api/system/system';
import { bindUserRole, getUserRoleList } from '#/api/system/user';

import { useRoleBindFormSchema, useRoleGridColumns } from '../data';

// 用户信息
const userData = ref<UserApi.User>();
const systemList = ref<SystemApi.System[]>([]);

// 获取动态标题
const getTitle = computed(() => {
  return userData.value ? `绑定角色 - ${userData.value.userName}` : '绑定角色';
});

/** Switch组件状态变更回调 */
async function onSwitchChange(newVal: boolean, row: any) {
  if (!userData.value?.id) {
    ElMessage.error('用户信息异常');
    return false;
  }

  const bindStatus = newVal ? 1 : 0;
  const action = bindStatus === 1 ? '绑定' : '解绑';

  try {
    await bindUserRole({
      userId: userData.value.id,
      roleId: row.id,
      bindStatus,
    });
    ElMessage.success(`${action}成功`);
    // 更新行数据
    row.isBound = bindStatus;
    return true;
  } catch {
    ElMessage.error(`${action}失败`);
    return false;
  }
}

/** 刷新表格 */
function onRefresh() {
  gridApi.query();
}

/** 加载系统列表 */
async function loadSystemList() {
  try {
    const { list } = await getSystemList({ pageNum: 1, pageSize: 999 });
    systemList.value = list;

    // 更新搜索表单的系统选项
    await gridApi.formApi.updateSchema([
      {
        fieldName: 'systemId',
        label: '所属平台',
        component: 'Select',
        componentProps: {
          placeholder: '请选择平台进行筛选',
          allowClear: true,
          options: list.map((item) => ({
            label: item.name,
            value: item.id,
          })),
        },
      },
    ]);
  } catch (error) {
    console.error('加载系统列表失败:', error);
  }
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useRoleBindFormSchema(),
  },
  gridOptions: {
    columns: useRoleGridColumns(onSwitchChange),
    height: 'auto',
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          if (!userData.value?.id) {
            return { list: [], total: 0 };
          }

          // 调用新的用户角色列表接口，后端从token中获取用户信息，直接返回包含isBound状态的角色列表
          const result = await getUserRoleList({
            pageNum: page.currentPage,
            pageSize: page.pageSize,
            userId: userData.value.id,
            ...formValues,
          });

          return {
            list: result.list,
            total: result.total,
          };
        },
      },
    },
    rowConfig: {
      keyField: 'id',
    },
  } as VxeTableGridOptions<any>,
});

// 创建抽屉
const [Drawer, drawerApi] = useVbenDrawer({
  async onConfirm() {
    // 绑定角色抽屉的确认操作 - 直接关闭抽屉
    await drawerApi.close();
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      userData.value = undefined;
      return;
    }

    // 确保系统列表已加载
    if (systemList.value.length === 0) {
      await loadSystemList();
    }

    // 加载用户数据
    const data = drawerApi.getData<UserApi.User>();
    userData.value = data;

    // 设置表单默认值
    await gridApi.formApi.setValues({
      userId: data?.id,
    });

    // 等待Grid组件初始化完成后刷新数据
    await nextTick();
    onRefresh();
  },
});
</script>

<template>
  <Drawer :title="getTitle" class="w-1/2">
    <Grid table-title="角色列表" />
  </Drawer>
</template>
